package com.zzyl.nursing.controller.member;

import com.zzyl.common.annotation.Log;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.enums.BusinessType;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.poi.ExcelUtil;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.member.IMemberReservationService;
import com.zzyl.nursing.vo.member.MemberReservationPageVo;
import com.zzyl.nursing.vo.member.TimeSlotCountVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/member/reservation")
@Api(tags =  "预约信息相关接口")
public class MemberReservationController extends BaseController
{
    @Autowired
    private IMemberReservationService  reservationService;
    /**
     * 查询预约信息列表
     */
    @ApiOperation("查询预约信息列表")
    @PreAuthorize("@ss.hasPermi('member:reservation:list')")
    @GetMapping("/list")
    public TableDataInfo<List<Reservation>> list(@ApiParam("预约信息查询条件") Reservation reservation)
    {
        startPage();
        List<Reservation> list = reservationService.selectReservationList(reservation);
        return getDataTable(list);
    }

    /**
     * 导出预约信息列表
     */
    @ApiOperation("导出预约信息列表")
    @PreAuthorize("@ss.hasPermi('member:reservation:export')")
    @Log(title = "预约信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@ApiParam(value = "预约信息查询条件") HttpServletResponse response, Reservation reservation)
    {
        List<Reservation> list = reservationService.selectReservationList(reservation);
        ExcelUtil<Reservation> util = new ExcelUtil<Reservation>(Reservation.class);
        util.exportExcel(response, list, "预约信息数据");
    }

    /*
     *分页查询增加预约人姓名，手机号，状态，类型的查询条件
     */
    @GetMapping("/page")
    @ApiOperation("分页查询预约")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "int", paramType = "query"),
    })
    public R<TableDataInfo> findByPage(@RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "10") int pageSize,
                                       @RequestParam(required = false) Integer status ) {
        TableDataInfo tableDataInfo = reservationService.findByPage(pageNum, pageSize, status);
        return R.ok(tableDataInfo);
    }

    @ApiOperation("获取预约信息详细信息")
    @PreAuthorize("@ss.hasPermi('member:reservation:query')")
    @GetMapping(value = "/{id:[0-9]+}")  // 只匹配数字
    public R<Reservation> getInfo(@ApiParam("预约信息ID") @PathVariable("id") Long id)
    {
        return R.ok(reservationService.selectReservationById(id));
    }

    @ApiOperation("删除预约信息")
    @PreAuthorize("@ss.hasPermi('member:reservation:remove')")
    @Log(title = "预约信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@ApiParam("预约信息ID数组") @PathVariable Long[] ids)
    {
        return toAjax(reservationService.deleteReservationByIds(ids));
    }


    /**
     * 查询当天取消预约数量
     */
    @GetMapping("/cancelled-count")
    @ApiOperation("查询取消预约数量")
    public R<Integer> getCancelledReservationCount() {
        Long userId = UserThreadLocal.getUserId();
        Integer count = reservationService.getCancelledCountForToday(userId);
        return R.ok(count);
    }

    /**
     * 查询每个时间段剩余预约次数
     */
    @ApiOperation("查询每个时间段剩余预约次数")
    @GetMapping("/countByTime")
    public R<List<TimeSlotCountVo>> getCountByTime() {
        List<TimeSlotCountVo> result = reservationService.getReservationCountByTime();
        return R.ok(result);
    }

    /**
     * 新增预约
     */
    @ApiOperation("新增预约")
    @PostMapping
    public R<String> addReservation(@ApiParam("预约信息") @RequestBody Reservation reservation) {
        // 获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            return R.fail("用户未登录");
        }

        // 设置创建者
        reservation.setCreateBy(String.valueOf(userId));

        // 调用服务层新增预约
        boolean result = reservationService.addReservation(reservation);
        if (result) {
            return R.ok("预约成功");
        } else {
            return R.fail("预约失败，该时间段已约满或超过取消次数限制");
        }
    }




    /**
     * 取消预约
     */
    @ApiOperation("取消预约")
    @PutMapping("/{id}/cancel")
    public R<String> cancelReservation(@PathVariable Long id) {
        // 获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            return R.fail("用户未登录");
        }

        // 调用服务层取消预约
        boolean result = reservationService.cancelReservation(id, userId);

        if (result) {
            return R.ok("操作成功");
        } else {
            return R.fail("取消失败");
        }
    }

}